import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/views/Layout.vue'),
    meta: { requiresAuth: true },
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表板' }
      },
      {
        path: '/users',
        name: 'UserManagement',
        component: () => import('@/views/UserManagement.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: '/activities',
        name: 'ActivityManagement',
        component: () => import('@/views/ActivityManagement.vue'),
        meta: { title: '活动管理' }
      },
      {
        path: '/votes',
        name: 'VoteManagement',
        component: () => import('@/views/VoteManagement.vue'),
        meta: { title: '投票管理' }
      },
      {
        path: '/products',
        name: 'ProductManagement',
        component: () => import('@/views/ProductManagement.vue'),
        meta: { title: '商品管理' }
      },
      {
        path: '/orders',
        name: 'OrderManagement',
        component: () => import('@/views/OrderManagement.vue'),
        meta: { title: '订单管理' }
      },
      {
        path: '/content',
        name: 'ContentManagement',
        component: () => import('@/views/ContentManagement.vue'),
        meta: { title: '内容管理' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    next('/login')
  } else if (to.path === '/login' && authStore.isLoggedIn) {
    next('/dashboard')
  } else {
    next()
  }
})

export default router